package com.journaldev.threadpool.jianshu;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * SimpleDateFormat基于java8的解决方案
 * 摘自：https://mp.weixin.qq.com/s/WMGdon-ygEfV3xb9EjGv6w
 * <p>
 * Created by chenhs on 2019/4/24.
 * <p>
 * <p>
 * 阿里规约：
 * 如果是JDK8的应用，可以使用Instant代替Date，LocalDateTime代替Calendar，DateTimeFormatter代替Simpledateformatter，
 * 官方给出的解释：simple beautiful strong immutable thread-safe。
 **/
public class SimpleDateFormatTest2 {

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public static String formatDate2(LocalDateTime date) {
        return FORMATTER.format(date);
    }

    public static LocalDateTime parse2(String dateNow) {
        return LocalDateTime.parse(dateNow, FORMATTER);
    }

    public static void main(String[] args) throws InterruptedException {

        //System.out.println(formatDate2(LocalDateTime.now()));

        /**
         * 20个线程
         * Exception in thread "pool-1-thread-13" java.lang.NumberFormatException: multiple points
         */
        ExecutorService service = Executors.newFixedThreadPool(100);
        for (int i = 0; i < 20; i++) {
            service.execute(() -> {
                for (int j = 0; j < 10; j++) {
                    System.out.println(formatDate2(LocalDateTime.now()));
                }
            });
        }
        //等待上述线程执行完
        service.shutdown();
        service.awaitTermination(1, TimeUnit.DAYS);

    }
}
